package com.api.workflow.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.workflow.util.YNHttpUtils;
import org.apache.dubbo.common.utils.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.text.SimpleDateFormat;
import java.util.*;
/*
 *OA-18.无订单付款结算申请
 * 接口5 OA与SAP付款申请接口
 */
public class YN18FII002Action extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        BaseBean baseBean = new BaseBean();
        //获取请求ID
        String requestid = requestInfo.getRequestid();
        String lcbh = requestInfo.getWorkflowid();
        int formid = requestInfo.getRequestManager().getFormid();
        int formidAbs = Math.abs(formid);// 流程表单id绝对值
        String tableDBName ="formtable_main_"+formidAbs;
        // 主表数据
        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
        Property[] property = mainTableInfo.getProperty();
        //这里是存储了主表全部的数据  可自行修改存储结构
        Map<String, Object> mainTableInfoMap = new HashMap<>();
        List<Map<String, Object>> mainTableMap = getMaps(requestInfo);
        for (int i = 0; i < property.length; i++) {
            String name = property[i].getName().toLowerCase();
            mainTableInfoMap.put(name, Util.null2String(property[i].getValue()));
        }
        baseBean.writeLog("lyh:OA-18=============mainTableInfoMap:"+ JSONObject.toJSONString(mainTableInfoMap));

        //明细表数据
        List<Map<String, Object>> detailTableMap = getMaps(requestInfo);
        //业务逻辑
        String MESSAGE="";
        try {
            RecordSet rs=new RecordSet();
            Map<String,Object> map=new HashMap<>();
            //ZYF
            String zyf = String.valueOf(mainTableInfoMap.get("zyf"));
            map.put("ZSFFK","Y");

            map.put("ZBONO",mainTableInfoMap.get("lcbh"));
            map.put("ZREID",requestid);
            String sqr=mainTableInfoMap.get("sqr").toString();
            //设置部门ID
            String departmentid=" ";
            String sql1= "select * from hrmresource where id = '" + sqr + "'";
            baseBean.writeLog("lyh:OA-18================sql1"+sql1);
            rs.execute(sql1);
            if (rs.next()) {
                map.put("ZHRNO",rs.getString("workcode"));
                map.put("ZNAME",rs.getString("lastname"));
                departmentid = rs.getString("departmentid");
                baseBean.writeLog("lyh:OA-18=============ZHRNO"+rs.getString("workcode")+"ZNAME"+rs.getString("lastname"));
            }
            map.put("ZBOTYP", mainTableInfoMap.get("djlx"));
            map.put("LIFNR", mainTableInfoMap.get("gysxx"));
            map.put("WAERS", mainTableInfoMap.get("hb"));
            map.put("BUKRS", mainTableInfoMap.get("gsdm"));
            map.put("ZAPDAT", mainTableInfoMap.get("sqrq"));
            map.put("ZHXSUM", mainTableInfoMap.get("hxyfje"));

            //设置当前日期为审批日期
            Date currentDate = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = dateFormat.format(currentDate);
            map.put("ZPASSDAT", formattedDate);

            map.put("ZBKTXT", mainTableInfoMap.get("fksm"));
            map.put("ZLSCH",mainTableInfoMap.get("fkfs"));
            map.put("ZAZBET",mainTableInfoMap.get("hjhsje"));
            map.put("NUMPG",mainTableInfoMap.get("fpzs"));
            map.put("KURSF",mainTableInfoMap.get("hl"));
            map.put("BKVID",mainTableInfoMap.get("yxbs"));
            map.put("ZPARBANKL",mainTableInfoMap.get("skzhlxh"));
            map.put("ZPARBANKN",mainTableInfoMap.get("skrzh"));
            map.put("ZPARKOINH",mainTableInfoMap.get("zhcyr"));
            map.put("ZPARBANKA",mainTableInfoMap.get("zhmc"));
            //通过申请部门ID获取部门信息
            String sql2 = "select * from hrmdepartment where id = '" + departmentid + "'";
            baseBean.writeLog("lyh:OA-18==============sql21232"+sql2);
            rs.execute(sql2);
            if (rs.next()) {
                map.put("ZSQBM", rs.getString("departmentcode"));
                map.put("ZBMMS", rs.getString("departmentname"));
                baseBean.writeLog("lyh:OA-18============ZSQBM" + rs.getString("departmentcode") + "ZBMMS:" + rs.getString("departmentname"));
            }
            //处理明细表数据

            ArrayList<Map> list = new ArrayList<>();
            int count =1;
            String ZZBONO="";
            for (Map<String, Object> stringObjectMap : detailTableMap) {
                Map<String,Object> ITEM=new HashMap<>();
                if (!stringObjectMap.containsKey("fph") && !stringObjectMap.containsKey("jxzcje")){
                    if (StringUtils.isNoneEmpty(ZZBONO)){
                        ZZBONO=String.valueOf(stringObjectMap.get("xzyfdh"));
                    }
                    continue;
                }
                ITEM.put("BUZEI",count);
                count++;
                ITEM.put("ZEXTYPE",stringObjectMap.get("fylx"));
                ITEM.put("ZNUM",stringObjectMap.get("fph"));
                ITEM.put("ZBLDAT",stringObjectMap.get("fprq"));
                ITEM.put("WRBTR",stringObjectMap.get("je"));
                ITEM.put("ZWRBTR",stringObjectMap.get("jxzcje"));
                ITEM.put("WMWST",stringObjectMap.get("se"));
                ITEM.put("ZSL",stringObjectMap.get("sl"));
                ITEM.put("AUFNR",stringObjectMap.get("nbddbh"));
                ITEM.put("SGTXT",stringObjectMap.get("zy"));
                ITEM.put("KOSTL",stringObjectMap.get("cbzx"));
                ITEM.put("ZMENGE",stringObjectMap.get("sl"));
                ITEM.put("ZZ005", stringObjectMap.get("zzhth"));
                writeLog(ITEM+"ITEMITEMITEM");
                list.add(new HashMap<>(ITEM));
            }
            writeLog(list+"listlistlistlist");
            map.put("ITEMS",list);
            map.put("ZZBONO",ZZBONO);
            JSONObject object = new JSONObject(map);
            baseBean.writeLog("lyh:OA-18============object" + object.toJSONString());
            //调用HTTP工具类发送请求
            String post = YNHttpUtils.FII002(object.toJSONString(), YNHttpUtils.token());
            JSONObject jsonObject = JSONObject.parseObject(post);
            String STATUS = jsonObject.getString("STATUS");
            MESSAGE = jsonObject.getString("MESSAGE");

            JSONObject jsonObject1 = jsonObject.getJSONObject("RETURN");

            //这个接口的状态判断在RETURN 里
            String ZBONOSTATUS = jsonObject1.getString("STATUS");
            String ZBONOMESSAGE = jsonObject1.getString("MESSAGE");

            RecordSet recordSet = new RecordSet();
            //修改主表参数
            String updateMainTableName = "update " + tableDBName + " set qqcsx = ? , fhjgx = ? ,qqy=?, fhy = ? where  requestid = ? ";
            recordSet.executeUpdate(updateMainTableName, object.toString(), post, object.toString(),post,requestid);

            baseBean.writeLog("wyq==========updateMainTableName"+updateMainTableName);


            if (!"S".equals(ZBONOSTATUS)) {
                requestInfo.getRequestManager()
                        .setMessageid(requestInfo.getRequestid()+"OA-18");
                requestInfo.getRequestManager().setMessagecontent("SAP接口异常，请联系SAP人员，错误信息提示:："+ZBONOMESSAGE);
                return Action.FAILURE_AND_CONTINUE;
            }


            String BELNR = jsonObject1.getString("BELNR");
            String update = "update " + tableDBName + " set sappzh = '" + BELNR + "' where requestid = '" + requestid + "'";
            baseBean.writeLog("lyh==============update" + update);
//            rs.executeUpdate(update);



        } catch (Exception e) {
            baseBean.writeLog("wyq=========exc"+e.toString());
            requestInfo.getRequestManager()
                    .setMessageid(requestInfo.getRequestid()+"OA-18");
            requestInfo.getRequestManager().setMessagecontent("OA接口异常："+e.toString());
            return Action.FAILURE_AND_CONTINUE;
        }


        return Action.SUCCESS;

    }

    /**
     * 提取明细表全部的数据
     * @param requestInfo
     * @return
     */
    private static List<Map<String, Object>> getMaps(RequestInfo requestInfo) {
        DetailTable[] detailTable = requestInfo.getDetailTableInfo().getDetailTable();
        //这里是存储了全部的明细表数据  可自行修改存储结构
        List<Map<String, Object>> detailTableMap = new ArrayList<>();
        if (detailTable.length > 0) {
            for (int i = 0; i < detailTable.length; i++) {
                DetailTable dt = detailTable[i];
                Row[] s = dt.getRow();
                for (int j = 0; j < s.length; j++) {
                    Row r = s[j];
                    Cell c[] = r.getCell();
                    Map<String, Object> objectObjectHashMap = new HashMap<>();
                    for (int k = 0; k < c.length; k++) {
                        Cell c1 = c[k];
                        String name = c1.getName().toLowerCase();
                        String value = c1.getValue();
                        objectObjectHashMap.put(name, value);
                    }
                    detailTableMap.add(objectObjectHashMap);
                }
            }
        }
        return detailTableMap;
    }
}
